/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年05月27日 01:16:08
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年08月27日 14:32:53
 * @FilePath: \Mood-Blog-System\back\routes\index.js
 * @Description:  路由文件入口文件
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
const Router = require('koa-router');
const router = new Router();
const logger = require('../log4');
const LoginController = require('../controllers');
const { success, fail, getPositionByIp } = require('../util/core');
const { autoTransaction } = require('../util/db');
const app = require('./index');
const { verifyToken } = require('../util/jwt');
app.context = {};

router.prefix('/api');

router.get('/getUserInfo/:token', async (ctx, next) => {
    const { data, error } = verifyToken(ctx.request.params.token);
    if (error) {
        fail(ctx, 'token验证失败', 4000);
    } else {
        success(ctx, data, 'token验证成功');
    }
    await next();
})

router.post('/login', async (ctx, next) => {
    console.log(app.context);
    await LoginController.login(ctx);
    await next();
})

router.post('/register', async (ctx, next) => {
    console.log(app.context);
    await LoginController.register(ctx);
    await next();
})

router.get('/getPositionByIp/:ip', async (ctx, next) => {
    ctx.body = await getPositionByIp(ctx.request.params.ip);
    await next();
})

router.post('/sendEmailVerify/:toEmail', async (ctx, next) => {
    const { sendEmail } = require('../util/mailer');
    const { generateRandomCode } = require('../util/core');
    const { email } = require('../config');
    const expireTime = Date.now() + email.expireTime;
    const to = ctx.request.params.toEmail;
    const from = '568055454@qq.com';
    const authCode = email.authCode;
    const sendCode = await generateRandomCode(6);
    sendEmail(to, from, authCode, sendCode).then(res => {
        console.log('发送成功');
        app.context.emailVerify = { code: sendCode, expireTime };
    })
})

router.post('/upload', async (ctx, next) => {
    if (ctx.req.file) {
        ctx.req.file.url = `http://localhost:3000/uploads/${ctx.req.file.filename}`;
        const File = require('../models/File');
        await autoTransaction(async () => {
            ctx.req.file.user = ctx.user._id;
            ctx.req.file.page = ctx.req.body.page;
            const file = await File.create(ctx.req.file);
            success(ctx, file, '文件上传成功');
        }).catch(err => {
            fail(ctx, err);
        })
    } else {
        fail(ctx, '文件上传失败');
    }
    await next();
})

const webRouter = require('./web')({ Router, logger });
const restRouter = require('./rest')({ Router, logger });

router.use(webRouter.routes());
router.use(restRouter.routes());

module.exports = router;
